<?php

if (!defined('IN_XLP')) {
    exit('Access Denied!');
}

/**
 * Description of wxmenu
 * 微信企业号高级接口
 * @author xlp
 */
class qyApi {

    protected static $appId = null;  //企业CorpID，可在企业号后台设置中查看
    protected static $corpSecret = null;  //企业corpSecret，可在企业号后台设置->权限管理对应的管理组中查看
    protected static $menuData = null;
    protected static $city_id = 0;
    protected static $agentId = null; //应用ID，可在企业号后台应用中心对应的应用中查看
    protected static $departmentId = null; //制定部门id
    static $token = null;
    static $errCode = 0;
    static $errorMsg = null;
    static $accessTokenPre = 'token/weixin/qy/access_token_';

    //请求api前缀

    static function init($city_id) {
        $setting = F('steward/setting_city_' . $city_id);
        if (isHave($setting['corp_info'])) {
            $setting = $setting['corp_info'];
            if (isHave($setting['corpSecret']) && isHave($setting['corpID'])) {
                self::$city_id = $city_id;
                self::$appId = $setting['corpID'];
                self::$corpSecret = $setting['corpSecret'];
                self::$agentId = $setting['agentId'];
                self::$departmentId = $setting['departmentId'];
            } else {
                showError('api Error:请设置CorpId、CorpSecret');
            }
        } else {
            showError('api Error:请设置CorpId、CorpSecret');
        }
    }

    static function getErrorMsg() {
        return self::$errorMsg;
    }

    /**
     * 删除验证数据
     * @param string $appid
     */
    static public function resetAuth() {
        self::$token = '';
        S(self::$accessTokenPre . self::$appId, null);
        self::gettoken();
        return true;
    }

    /*
     * 检查是否需要重新获取accesstoken
     * 并记下日志
     */

    static public function checkAccessToken() {
        if (self::$errCode == 40001) {
            self::resetAuth();
            saveLog('qy/accessToken/reset', 'weixin.menu');
            return true;
        }
        return false;
    }

    static function gettoken() {
        if (self::$token) {
            return self::$token;
        }

        self::$token = S(self::$accessTokenPre . self::$appId);
        if (!self::$token) {
            $result = getHttp('https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' . self::$appId . '&corpsecret=' . self::$corpSecret);
            $result = json_decode($result, true);
            if ($result && !isset($result['errcode'])) {
                S(self::$accessTokenPre . self::$appId, $result['access_token'], $result['expires_in']);
                self::$token = $result['access_token'];
            } else {
                S(self::$accessTokenPre . self::$appId, $result['access_token'], $result['expires_in']);
                self::$errCode = $result['errcode'];
                self::$errorMsg = $result['errcode'];
                self::checkAccessToken();
                return false;
            }
        }
        return self::$token;
    }

    /*
     * 创建部门
     */

    static function departmentCreate($data) {
        self::gettoken();
        $data = self::encode_json($data);
        $result = getHttp("https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token=" . self::$token, $data);
        $result = json_decode($result, true);
        if ($result && !$result['errcode']) {
            return $result;
        } else {
            self::$errorMsg = $result['errcode'] . '-' . $result['errmsg'];
            return false;
        }
    }

    /*
     * 更新部门
     */

    static function departmentUpdate($data) {
        self::gettoken();
        $data = self::encode_json($data);
        $result = getHttp("https://qyapi.weixin.qq.com/cgi-bin/department/update?access_token=" . self::$token, $data);
        $result = json_decode($result, true);
        if ($result && !$result['errcode']) {
            return $result;
        } else {
            self::$errorMsg = $result['errcode'] . '-' . $result['errmsg'];
            return false;
        }
    }

    /*
     * 删除部门
     * id	是	部门id。（注：不能删除根部门；不能删除含有子部门、成员的部门）
     */

    static function departmentDelete($id) {
        self::gettoken();
        $result = getHttp("https://qyapi.weixin.qq.com/cgi-bin/department/delete?access_token=" . self::$token . "&id=" . $id);
        $result = json_decode($result, true);
        if ($result && !$result['errcode']) {
            return $result;
        } else {
            self::$errorMsg = $result['errcode'] . '-' . $result['errmsg'];
            return false;
        }
    }

    /*
     * 获取部门列表
     */

    static function departmentList($refresh = "") {
        $cacheKey = "departmentListCache_" . self::$city_id;
        $departmentList = F($cacheKey);
        if (!$departmentList || $refresh) {
            self::gettoken();
            $result = getHttp("https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=" . self::$token);
            $result = json_decode($result, true);
            if ($result && !$result['errcode']) {
                $departmentList = $result["department"];
                foreach ($departmentList as $dk => $dv) {
                    $templist[$dv['id']] = $dv;
                }
                if ($templist) {
                    unset($departmentList);
                    $departmentList = $templist;
                    F($cacheKey, $departmentList);
                }
            } else {
                self::$errorMsg = $result['errcode'] . '-' . $result['errmsg'];
                return false;
            }
        }
        return $departmentList;
    }

    /*
     * 创建成员
     */

    static function userCreate($data) {
        self::gettoken();
        if (!isHave($data['department'])) {
            if (self::$departmentId) {
                $data['department'] = array(self::$departmentId);
            } else {
                $data['department'] = array("1");
            }
        }
        $data = self::encode_json($data);
        $result = getHttp("https://qyapi.weixin.qq.com/cgi-bin/user/create?access_token=" . self::$token, $data);
        $result = json_decode($result, true);
        if ($result && !$result['errcode']) {
            return $result;
        } else {
            self::$errorMsg = $result['errcode'] . '-' . $result['errmsg'];
            return false;
        }
    }

    /*
     * 更新成员
     */

    static function userUpdate($data) {
        self::gettoken();
        $data = self::encode_json($data);
        $result = getHttp("https://qyapi.weixin.qq.com/cgi-bin/user/update?access_token=" . self::$token, $data);
        $result = json_decode($result, true);
        if ($result && !$result['errcode']) {
            return $result;
        } else {
            self::$errorMsg = $result['errcode'] . '-' . $result['errmsg'];
            return false;
        }
    }

    /*
     * 删除成员
     * userid	是	员工UserID。对应管理端的帐号
     */

    static function userDelete($userid) {
        self::gettoken();
        $result = getHttp("https://qyapi.weixin.qq.com/cgi-bin/user/delete?access_token=" . self::$token . "&userid=" . $userid);
        $result = json_decode($result, true);
        if ($result && !$result['errcode']) {
            return $result;
        } else {
            self::$errorMsg = $result['errcode'] . '-' . $result['errmsg'];
            return false;
        }
    }

    /*
     * 获取成员
     * userid	是	员工UserID。对应管理端的帐号
     */

    static function userGet($userid, $refresh = "") {
        //$cacheKey="userInfoCache_".self::$city_id."_".$userid;
        //$userInfo = F($cacheKey);
        //if (!$userInfo || $refresh) {
        self::gettoken();
        $result = getHttp("https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=" . self::$token . "&userid=" . $userid);
        $result = json_decode($result, true);
        if ($result && !$result['errcode']) {
            if ($result) {
                unset($result['errcode'], $result['errmsg']);
                /*
                  $department="";
                  foreach($result['department'] as $dk=>$dv){
                  $department.=$dv.",";
                  }
                  $result['department']=substr($department,0,-1);
                 */
                $result['extattr'] = json_encode($result['extattr']["attrs"]);
                $userInfo = $result;
                /*
                  if($info=M("qy_user")->where(array("userid"=>$userid))->findAll()){
                  $userInfo['uid']=$info[0]['uid'];
                  }else{
                  $lastid=M("qy_user")->insert($userInfo);
                  $info=M("qy_user")->where(array("userid"=>$userid))->findAll();
                  $userInfo['uid']=$info[0]['uid'];
                  }
                  F($cacheKey, $userInfo);
                 */
            }
        } else {
            self::$errorMsg = $result['errcode'] . '-' . $result['errmsg'];
            return false;
        }
        //}
        return $userInfo;
    }

    /*
     * 获取部门成员
     * departmentId	是	获取的部门id
     * fetchChild	是	1/0：是否递归获取子部门下面的成员
     * status	    是	0获取全部员工，1获取已关注成员列表，2获取禁用成员列表，4获取未关注成员列表。status可叠加
     */

    static function userSimplelist($refresh = "", $departmentId = 1, $fetchChild = 1, $status = 0) {
        $cacheKey = "userSimplelistCache_" . self::$city_id;
        $userSimplelist = F($cacheKey);
        if (!$userSimplelist || $refresh) {
            self::gettoken();
            $result = getHttp("https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?access_token=" . self::$token . "&department_id=" . $departmentId . "&fetch_child=" . $fetchChild . "&status=" . $status);
            $result = json_decode($result, true);
            if ($result && !$result['errcode']) {
                $userSimplelist = $result["userlist"];
                foreach ($userSimplelist as $dk => $dv) {
                    $templist[$dv['userid']] = $dv;
                    $exist = M("qy_user")->where(array("userid" => $dv['userid']))->findAll();
                    if ($exist) {
                        if ($dv['name'] != $exist[0]['name']) {
                            M("qy_user")->update(array("name" => $dv['name']), array("userid" => $dv['userid']));
                        }
                    } else {
                        M("qy_user")->insert(array("userid" => $dv['userid'], "name" => $dv['name']));
                    }
                }
                if ($templist) {
                    unset($userSimplelist);
                    $userSimplelist = $templist;
                    F($cacheKey, $userSimplelist);
                }
            } else {
                self::$errorMsg = $result['errcode'] . '-' . $result['errmsg'];
                return false;
            }
        }
        return $userSimplelist;
    }

    /*
     * 获取标签列表
     */

    static function tagList() {
        self::gettoken();
        $result = getHttp("https://qyapi.weixin.qq.com/cgi-bin/tag/list?access_token=" . self::$token);
        $result = json_decode($result, true);
        if ($result && !$result['errcode']) {
            return $result;
        } else {
            self::$errorMsg = $result['errcode'] . '-' . $result['errmsg'];
            return false;
        }
    }

    /*
     * 获取标签列表
     */

    static function tagGet($tagid) {
        self::gettoken();
        $result = getHttp("https://qyapi.weixin.qq.com/cgi-bin/tag/get?access_token=" . self::$token . "&tagid=" . $tagid);
        $result = json_decode($result, true);
        if ($result && !$result['errcode']) {
            return $result;
        } else {
            self::$errorMsg = $result['errcode'] . '-' . $result['errmsg'];
            return false;
        }
    }

    /*
     * 获取媒体文件
     */

    static function mediaGet($media_id) {
        self::gettoken();
        $result = getHttp("https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token=" . self::$token . "&media_id=" . $media_id);
        $result = json_decode($result, true);
        if ($result && !$result['errcode']) {
            return $result;
        } else {
            self::$errorMsg = $result['errcode'] . '-' . $result['errmsg'];
            return false;
        }
    }

    /*
     * 发送接口
     * 消息数据格式 http://qydev.weixin.qq.com/wiki/index.php?title=%E6%B6%88%E6%81%AF%E7%B1%BB%E5%9E%8B%E5%8F%8A%E6%95%B0%E6%8D%AE%E6%A0%BC%E5%BC%8F#mpnews.E6.B6.88.E6.81.AF
     */

    static function messageSend($msg) {
        self::gettoken();
        $msg['touser'] = $msg['touser'] ? $msg['touser'] : "";
        if (isHave($msg['toparty'])) {
            $msg['toparty'] = $msg['touser'];
        }
        if (isHave($msg['totag'])) {
            $msg['totag'] = $msg['totag'];
        }
        $msg['msgtype'] = isHave($msg['msgtype']) ? $msg['msgtype'] : "text";
        $msg['agentid'] = isHave($msg['agentid']) ? $msg['agentid'] : self::$agentId;
        $msg[$msg['msgtype']] = $msg[$msg['msgtype']];
        if (isHave($msg['safe'])) {
            $msg['safe'] = $msg['safe'];
        }
        $msg = self::encode_json($msg);
        $result = getHttp("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" . self::$token, $msg);
        $result = json_decode($result, true);
        if ($result && !$result['errcode']) {
            return $result;
        } else {
            self::$errorMsg = $result['errcode'] . '-' . $result['errmsg'];
            return false;
        }
    }

    //中文 json转码
    function encode_json($str) {
        return urldecode(json_encode(self::url_encode($str)));
    }

    //对数组urlencode
    function url_encode($str) {
        if (is_array($str)) {
            foreach ($str as $key => $value) {
                $str[urlencode($key)] = self::url_encode($value);
            }
        } else {
            $str = urlencode($str);
        }
        return $str;
    }

}
